package com.lsh.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/2/22 4:20 下午
 * @desc ：同步阻塞式I/O创建的TimeClient源码
 *
 * 客户端通过socket创建，发送查询时间服务器的"QUERY TIME ORDER"指令，
 * 然后读取服务端的响应并将结果打印出来，随后关闭连接，释放资源，程序退出执行
 *
 */
public class TineClient {
    public static void main(String[] args) {
        int port = 8888;
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        /**
         * 通过PrintWirter向服务器端发送"QUERY TIME ORDER"指令
         * 然后通过BufferReader的readLine读取响应并打印
         */
        try{
            socket = new Socket("127.0.0.1", port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(),true);
            out.println("QUERY TIME ORDER");
            System.out.println("TineClient1 Sned order 2 server succeed.");
            String resp = in.readLine();
            System.out.println("Now is "+resp);


        }catch (Exception e){
            //不需要处理
        }finally {
            if (out !=  null){
                out.close();
                out = null;
            }
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;

            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }

        }

    }
}
